package org.crepi22.finecrop;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * The Class Photo storing infos on the bitmap and the origin.
 */
public class Photo {
    
    /** The file. */
    final File file;
    
    /** The photo width. */
    int photoWidth;
    
    /** The photo height. */
    int photoHeight;
    
    /** The photo. */
    private BufferedImage photo;
    
    /**
     * Instantiates a new photo.
     *
     * @param file the file
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public Photo(File file) throws IOException {
        this.file = file;
        photo = ImageIO.read(file);
        if(photo == null) throw new IOException(Messages.getString("Photo.io_error") + file); //$NON-NLS-1$
        photoWidth = photo.getWidth();
        photoHeight = photo.getHeight();
    }
    
    
    /**
     * Produce a bound specification for cropping suitable for ImageMagick. Ensures that parameter are within bounds. Exchange points if necessary
     * @param sx left value
     * @param sy top value
     * @param ex right value
     * @param ey bottom value
     * @return specification
     */
    public String formatBounds(int sx, int sy, int ex, int ey) {
        sx = boundX(sx);
        sy = boundY(sy);
        ex = boundX(ex);
        ey = boundY(ey);
        return String.format("%dx%d+%d+%d",Math.abs(ex -sx),Math.abs(ey - sy),Math.min(sx, ex) , Math.min(sy,ey)); //$NON-NLS-1$
    }

    /**
     * Enforce that x is in the bound of the photo.
     *
     * @param x the x
     * @return the value in bounds
     */
    final private int boundX(int x) {
        return Math.max(0, Math.min(x,photoWidth));
    }

    /**
     * enforce that y is in the bound of the photo.
     *
     * @param y the y
     * @return the value in bounds
     */
    final private int boundY(int y) {
        return Math.max(0, Math.min(y,photoHeight));
    }
    
    /**
     * Gets the image.
     *
     * @return the image
     */
    final public BufferedImage getImage() {
        return photo;
    }
    
    /**
     * Gets the file.
     *
     * @return the file
     */
    final public File getFile() {
        return file;
    }
    
    /**
     * Gets the path.
     *
     * @return the path
     */
    final public String getPath() {
        return file.getAbsolutePath();
    }
}
